/**
 * jQuery EasyUI 1.4
 * 
 * Copyright (c) 2009-2014 www.jeasyui.com. All rights reserved.
 * 
 * Licensed under the GPL license: http://www.gnu.org/licenses/gpl.txt To use it
 * on other terms please contact us at info@jeasyui.com
 * 
 */
(function($) {
	function createCombogrid(target) {
		var combogrid = $.data(target, "combogrid");
		var opts = combogrid.options;
		var grid = combogrid.grid;
		$(target).addClass("combogrid-f").combo($.extend({},opts,{
			onShowPanel : function() {
				var p = $(this).combogrid("panel");
				var outerHeight = p.outerHeight()- p.height();
			var minHeight = p._size("minHeight");
			var maxHeight = p._size("maxHeight");
			$(this).combogrid("grid").datagrid("resize",{
						width : "100%",
						height : (isNaN(parseInt(opts.panelHeight)) ? "auto" : "100%"),
						minHeight : (minHeight ? minHeight - outerHeight : ""),
						maxHeight : (maxHeight ? maxHeight - outerHeight : "")
			});
			opts.onShowPanel.call(this);
		}}));
		var panel = $(target).combo("panel");
		if (!grid) {
			grid = $("<table></table>").appendTo(panel);
			combogrid.grid = grid;
		}
		var outerHeight = panel.outerHeight()- panel.height();
		var minHeight = panel._size("minHeight");
		var maxHeight = panel._size("maxHeight");
		grid.datagrid($.extend({}, opts, {
			width : "100%",
			height : (isNaN(parseInt(opts.panelHeight)) ? "auto" : "100%"),
			minHeight : (minHeight ? minHeight - outerHeight : ""),
			maxHeight : (maxHeight ? maxHeight - outerHeight : ""),
			//不清除默认选择上的内容
			checkOnSelect:true,
			selectOnCheck : true,
			showPageList:false,
			showPageStyle:"manual",
			border : false,
			singleSelect : (!opts.multiple),
			onLoadSuccess : function(_a) {
				var _b = $(target).combo("getValues");
				var _c = opts.onSelect;
				opts.onSelect = function() {
				};
				setValues(target, _b, combogrid.remainText);
				opts.onSelect = _c;
				opts.onLoadSuccess.apply(target, arguments);
			},
			onClickRow : clickRow,
			onSelect : function(_e, _f) {
				_select();
				opts.onSelect.call(this, _e, _f);
			},
			onUnselect : function(_11, row) {
				_select();
				opts.onUnselect.call(this, _11, row);
			},
			onSelectAll : function(rows) {
				_select();
				opts.onSelectAll.call(this, rows);
			},
			onUnselectAll : function(rows) {
				if (opts.multiple) {
					_select();
				}
				opts.onUnselectAll.call(this, rows);
			}
		}));
		function clickRow(_14, row) {
			combogrid.remainText = false;
			_select();
			if (!opts.multiple) {
				$(target).combo("hidePanel");
			}
			opts.onClickRow.call(this, _14, row);
		};
		function _select() {
			var _15 = grid.datagrid("getSelections");
			var vv = [], ss = [];
			opts.selectObject=[];
			for (var i = 0; i < _15.length; i++) {
				vv.push(_15[i][opts.idField]);
				ss.push(_15[i][opts.textField]);
				opts.selectObject.push(_15[i]);
			}
			if (!opts.multiple) {
				$(target).combo("setValues", (vv.length ? vv : [ "" ]));
			} else {
				$(target).combo("setValues", vv);
			}
			if (!combogrid.remainText) {
				$(target).combo("setText", ss.join(opts.separator));
			}
		};
	};
	function nav(target, dir) {
		var combogrid = $.data(target, "combogrid");
		var opts = combogrid.options;
		var grid = combogrid.grid;
		var len = grid.datagrid("getRows").length;
		if (!len) {
			return;
		}
		var tr = opts.finder.getTr(grid[0], null, "highlight");
		if (!tr.length) {
			tr = opts.finder.getTr(grid[0], null, "selected");
		}
		var _1b=null;
		if (!tr.length) {
			_1b = (dir == "next" ? 0 : len - 1);
		} else {
			var _1b = parseInt(tr.attr("datagrid-row-index"));
			_1b += (dir == "next" ? 1 : -1);
			if (_1b < 0) {
				_1b = len - 1;
			}
			if (_1b >= len) {
				_1b = 0;
			}
		}
		grid.datagrid("highlightRow", _1b);
		if (opts.selectOnNavigation) {
			combogrid.remainText = false;
			grid.datagrid("selectRow", _1b);
		}
	};
	function setValues(target, values, _1f) {
		var combogrid = $.data(target, "combogrid");
		var opts = combogrid.options;
		var grid = combogrid.grid;
		var rows = grid.datagrid("getRows");
		var checkeds = grid.datagrid("getChecked");
		var ss = [];
		var combOpts = $(target).combo("options");
		var onChange = combOpts.onChange;
		combOpts.onChange = function() {
		};
		if(!opts.rememberAll){
			grid.datagrid("clearSelections");
		}
		for (var i = 0; i < values.length; i++) {
			var rowId = grid.datagrid("getRowIndex", values[i]);
			if (rowId >= 0) {
				grid.datagrid("selectRow", rowId);
				ss.push(rows[rowId]);
			}
		}
		//查询是否在old选择
		for (var i = 0; i < values.length; i++) {
			var idF=values[i];
			for (var ci = 0; ci < checkeds.length; ci++) {
				if(checkeds[ci][opts.idField]==idF){
					var add=true;
					for(var chs=0;chs<ss.length;chs++){
						if(ss[chs][opts.idField]==idF){
							add=false;
							break;
						}
					}
					if(add){
						ss.push(checkeds[ci]);
					}
				}
			}
		}
		combOpts.onChange = onChange;
		//如果在list表中没有查询到
		if(ss && ss.length>0){
			opts.selectObject=ss;
			var oldId=[];
			var oldName=[];
			for (var n = 0; n < opts.selectObject.length; n++) {
				oldId.push(opts.selectObject[n][opts.idField]);
				oldName.push(opts.selectObject[n][opts.textField]);
			}
			$(target).combo("setValues", oldId.join(opts.separator));
			if (!_1f) {
				var s = oldName.join(opts.separator);
				if ($(target).combo("getText") != s) {
					$(target).combo("setText", s);
				}
			}
		}else{
			if($.isArray(opts.selectObject)){
				var oldId=[];
				var oldName=[];
				for (var n = 0; n < opts.selectObject.length; n++) {
					oldId.push(opts.selectObject[n][opts.idField]);
					oldName.push(opts.selectObject[n][opts.textField]);
				}
				$(target).combo("setValues", oldId.join(opts.separator));
				$(target).combo("setText", oldName.join(opts.separator));
			}else if(typeof opts.selectObject == "string"){
				var seleObj=$.getJSON(opts.selectObject);
				if(seleObj){
					opts.selectObject=seleObj;
					$(target).combo("setValues", opts.selectObject[opts.idField]);
					$(target).combo("setText", opts.selectObject[opts.textField]);
				}
			}else{
				if(opts.selectObject){
					$(target).combo("setValues", opts.selectObject[opts.idField]);
					$(target).combo("setText", opts.selectObject[opts.textField]);
				}
			}
		}
	};
	function query(target, q) {
		var combogrid = $.data(target, "combogrid");
		var opts = combogrid.options;
		var grid = combogrid.grid;
		combogrid.remainText = true;
		if (opts.multiple && !q) {
			setValues(target, [], true);
		} else {
			setValues(target, [ q ], true);
		}
		if (opts.mode == "remote") {
			grid.datagrid("clearSelections");
			grid.datagrid("load", $.extend({}, opts.queryParams, {
				q : q
			}));
		} else {
			if (!q) {
				return;
			}
			grid.datagrid("clearSelections").datagrid("highlightRow", -1);
			var _2d = grid.datagrid("getRows");
			var qq = opts.multiple ? q.split(opts.separator) : [ q ];
			$.map(qq, function(q) {
				q = $.trim(q);
				if (q) {
					$.map(_2d, function(row, i) {
						if (q == row[opts.textField]) {
							grid.datagrid("selectRow", i);
						} else {
							if (opts.filter.call(target, q, row)) {
								grid.datagrid("highlightRow", i);
							}
						}
					});
				}
			});
		}
	};
	function enter(target) {
		var combogrid = $.data(target, "combogrid");
		var opts = combogrid.options;
		var grid = combogrid.grid;
		var tr = opts.finder.getTr(grid[0], null, "highlight");
		combogrid.remainText = false;
		if (tr.length) {
			var row = parseInt(tr.attr("datagrid-row-index"));
			if (opts.multiple) {
				if (tr.hasClass("datagrid-row-selected")) {
					grid.datagrid("unselectRow", row);
				} else {
					grid.datagrid("selectRow", row);
				}
			} else {
				grid.datagrid("selectRow", row);
			}
		}
		var vv = [];
		$.map(grid.datagrid("getSelections"), function(row) {
			vv.push(row[opts.idField]);
		});
		$(target).combogrid("setValues", vv);
		if (!opts.multiple) {
			$(target).combogrid("hidePanel");
		}
	};
	$.fn.combogrid = function(options, param) {
		if (typeof options == "string") {
			var method = $.fn.combogrid.methods[options];
			if (method) {
				return method(this, param);
			} else {
				return this.combo(options, param);
			}
		}
		options = options || {};
		return this.each(function() {
			var combogrid = $.data(this, "combogrid");
			if (combogrid) {
				$.extend(combogrid.options, options);
			} else {
				combogrid = $.data(this, "combogrid", {
					options : $.extend({}, $.fn.combogrid.defaults,$.fn.combogrid.parseOptions(this), options)
				});
			}
			createCombogrid(this);
		});
	};
	$.fn.combogrid.methods = {options : function(jq) {
			var opts = jq.combo("options");
			return $.extend($.data(jq[0], "combogrid").options, {
				width : opts.width,
				height : opts.height,
				originalValue : opts.originalValue,
				disabled : opts.disabled,
				readonly : opts.readonly
			});
		},
		grid : function(jq) {
			return $.data(jq[0], "combogrid").grid;
		},
		loadGrid : function(jq, param) {
			return jq.each(function() {
				$(this).combogrid("grid").datagrid("load",param);
			});
		},
		setValues : function(jq, _39) {
			return jq.each(function() {
				setValues(this, _39);
			});
		},
		setValue : function(jq, _3a) {
			return jq.each(function() {
				setValues(this, [ _3a ]);
			});
		},
		clear : function(jq) {
			return jq.each(function() {
				var opts = $(this).combogrid("options");
				$(this).combogrid("grid").datagrid("clearSelections");
				$(this).combo("clear");
				opts.selectObject=new Array();
			});
		},
		reset : function(jq) {
			return jq.each(function() {
				var opts = $(this).combogrid("options");
				if (opts.multiple) {
					$(this).combogrid("setValues", opts.originalValue);
				} else {
					$(this).combogrid("setValue", opts.originalValue);
				}
			});
		}
	};
	$.fn.combogrid.parseOptions = function(target) {
		return $.extend({}, $.fn.combo.parseOptions(target), $.fn.datagrid.parseOptions(target), $.parser.parseOptions(target, [ "idField","textField", "mode" ]));
	};
	$.fn.combogrid.defaults = $.extend({}, $.fn.combo.defaults,$.fn.datagrid.defaults, {
		loadMsg : null,
		idField : null,
		textField : null,
		//是否记住全部选择内容
		rememberAll : false,
		mode : "local",
		keyHandler : {
			up : function(e) {
				nav(this, "prev");
				e.preventDefault();
			},
			down : function(e) {
				nav(this, "next");
				e.preventDefault();
			},
			left : function(e) {
			},
			right : function(e) {
			},
			enter : function(e) {
				enter(this);
			},
			query : function(q, e) {
				query(this, q);
			}
		},
		filter : function(q, row) {
			var opts = $(this).combogrid("options");
			return row[opts.textField].toLowerCase().indexOf(q.toLowerCase()) == 0;
		}
	});
})(jQuery);
